#include <iostream>
#include <unistd.h>
#include <pthread.h>

int board;

pthread_rwlock_t rw;

using namespace std;

void* Reader(void* argv)
{
    const char* name = static_cast<char*>(argv);
    cout << "run..." << endl;
    sleep(1);
    while (true)
    {
        pthread_rwlock_rdlock(&rw);
        cout << "reader read: " << board << endl;
        sleep(10);
        pthread_rwlock_unlock(&rw);
    }
}

void* Writer(void* argv)
{
   const char* name = static_cast<char*>(argv);
   cout << "run..." << endl;
   while (true)
   {
       pthread_rwlock_wrlock(&rw);
       board++;
       cout <<"I am Writer" << endl;
       sleep(10);
       pthread_rwlock_unlock(&rw);
       sleep(1);
   }
}

int main()
{
    pthread_rwlock_init(&rw, nullptr);
    pthread_t r1, r2, r3, r4, r5, w;
    pthread_create(&r1, nullptr, Reader,(void*)"reader");
    pthread_create(&r2, nullptr, Reader,(void*)"reader");
    pthread_create(&r3, nullptr, Reader,(void*)"reader");
    pthread_create(&r4, nullptr, Reader,(void*)"reader");
    pthread_create(&r5, nullptr, Reader,(void*)"reader");
    pthread_create(&w, nullptr, Writer, (void*)"Writer");

    pthread_join(r1, nullptr);
    pthread_rwlock_destroy(&rw);
    return 0;
}
